//
//  UserCount.swift
//  WeiBo2017
//
//  Created by 王璐 on 2017/4/26.
//  Copyright © 2017年 wl. All rights reserved.
//

import UIKit

//用户账户Key
fileprivate let WLUserCount = "cn.wl.userCount"

class UserCount: NSObject {
    
    //用户账户单例
    static let sharedUserCount = UserCount()
    
    //用户登录标记
    var isLogin : Bool{
        return access_token != nil
    }
    
    /// 用户授权的唯一票据，用于调用微博的开放接口
    var access_token:String?
    /// access_token的生命周期，单位是秒数。 string
    //从应用创建时间开始
    var expires_in:TimeInterval = 0{
        didSet{
            //计算过期日期
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///过期日期
    var expiresDate:NSDate?
    /// 授权用户的UID
    var uid:String?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    private override init() {
        super.init()
        
        loadUserCount()
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
    
    override var description: String{
        
        //属性数组
        let keys = ["access_token","expires_in","expiresDate","uid","screen_name","avatar_large"]
        //模型转字典
        return dictionaryWithValues(forKeys: keys).description
    }
}

// MARK: - 加载或保存用户账户
extension UserCount{
    
    /// 使用字典更新模型数据
    ///
    /// - parameter dict: 字典
    func updateUserAccount(dict:[String:AnyObject]){
        
        setValuesForKeys(dict)
        
        saveUserCount()
    }
    
    
    fileprivate func saveUserCount() {
        
        let keys = ["access_token","expiresDate","uid","screen_name","avatar_large"]
        //模型转字典
        let dict = dictionaryWithValues(forKeys: keys)
        //将字典写入偏好设置
        UserDefaults.standard.set(dict, forKey: WLUserCount)
        print(NSHomeDirectory())
    }
    
   fileprivate func loadUserCount(){
    
    //1.从偏好中加载
    guard let dict = UserDefaults.standard.object(forKey: WLUserCount) as? [String:AnyObject] else {
        return
    }
    //2.字典转模型
    setValuesForKeys(dict)
    //3.判断是否过期,如果过期,将access_token设置为nil
    if isExpired {
        print("过期")
        access_token = nil
    }else{
        print("正常")
    }
    
    }
    
    fileprivate var isExpired:Bool{
        return expiresDate?.compare(NSDate() as Date) == ComparisonResult.orderedAscending
    }
}
